import "./index.css";
import { PageContext } from "../../store/index";
import { useContext } from "react";
import { v4 } from "uuid";
import { componentsList } from "../../components/index";

export const Editor = () => {
  const { list, setList, setCurrentConfigId } = useContext(PageContext);

  const handleDragOver = (e) => {
    e.preventDefault();
  };

  const handleDrop = (e) => {
    const droppedElementName = e.dataTransfer.getData("text/plain");
    console.log(">>>droppedElementName", droppedElementName);

    setList(
      list.concat({
        id: v4(),
        name: droppedElementName,
        props: {},
        style: {},
        children: [],
      })
    );
  };

  const getComponent = (name) => {
    return componentsList.find((item) => item.name === name);
  };

  const handleConfig = (id) => {
    setCurrentConfigId(id);
  }

  const renderComponents = () => {
    return list.map((item) => {
      const Component = getComponent(item.name).component;
      return (
        <span onClick={() => handleConfig(item.id)}>
          <Component key={item.name} {...item.props} />
        </span>
      );
    });
  };

  return (
    <div
      className="editor-container"
      onDragOver={handleDragOver}
      onDrop={handleDrop}
    >
      {renderComponents()}
    </div>
  );
};
